<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="700px" @ok="handleSubmit" showFooter destroyOnClose>
    <BasicForm @register="registerForm">
      <template #batchNo="{ model, field }">
        <a-row>
          <a-col :span="22">
            <a-input v-model:value="model[field]" placeholder="批次号, eg: 24061801" />
          </a-col>
          <a-col :span="2" class="flex">
            <a-button type="link" size="middle" @click="getTodayBatchNo(model, field)"> 今日 </a-button>
          </a-col>
        </a-row>
      </template>

      <template #fixedFlag="{ model, field }">
        <a-form-item-rest>
          <MyRadioGroup v-model:value="model[field]" :options="fixedFlagOptions" />
          <a-input v-if="model[field] === '1'" suffix="￥" v-model:value="model['fixedPayAmount']" style="width: 140px" size="small" />
        </a-form-item-rest>
      </template>

      <template #urlPlaceholder="{ model, field }">
        <div class="flex">
          <span>{{ model["qrcodePrefix"] }}</span>
          <span v-if="(!(model['qrcodePrefix'] as string).endsWith('/') && model[field]) || showUpdateUrlPlaceholder">/</span>
          <a-input size="small" class="mr-2 ml-2" v-if="showUpdateUrlPlaceholder" placeholder="占位符" v-model:value="model[field]" />
          <span v-else>{{ model[field] }}</span>
          <!-- <span v-if="!model[field] || model[field] === ''"></span>
          <span v-else>/</span> -->
          <span>{{ `${model["qrcodeSuffix"]}/${model["entryPage"]}` }}</span>
          <a-button v-if="model.entryPage != 'h5'" size="small" type="link" @click="() => (showUpdateUrlPlaceholder = !showUpdateUrlPlaceholder)">
            {{ showUpdateUrlPlaceholder ? "确认" : "修改" }}
          </a-button>
        </div>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, useAttrs } from "vue"
  import { BasicForm, useForm, MyRadioGroup } from "/@/components/Form/index"
  import { inputFormSchemas, fixedFlagOptions } from "./qrcode.data"
  import { BasicDrawer, useDrawerInner } from "/@/components/Drawer"
  import { saveOrUpdateMchQrcode, getMchQrcode } from "/@/api"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { getConfigByKey } from "/@/api/infra/config"
  import { TenantType } from "/@/enums/bizEnum"
  import { dateUtil } from "/@/utils/dateUtil"
  import { ColEx } from "/@/components/Form/src/types"
  const { createMessage } = useMessage()

  const emit = defineEmits(["success", "register"])
  const attrs = useAttrs()
  const isUpdate = ref(true)
  const record = ref<any>({})

  const showUpdateUrlPlaceholder = ref<boolean>(false)

  const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    schemas: inputFormSchemas,
    showActionButtonGroup: false,
    wrapperCol: {
      md: { span: 22 },
      sm: { span: 22 },
    },
  })

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    await resetFields()
    record.value = data.record
    setDrawerProps({ confirmLoading: false, loading: true })
    try {
      isUpdate.value = !!data?.isUpdate
      const configInfo = await getConfigByKey("trade", TenantType.MANAGE)
      if (!configInfo) {
        createMessage.error("当前管理端尚未配置交易, 请联系管理员")
        closeDrawer()
        return
      }

      const configValue = JSON.parse(configInfo.configValue)
      if (unref(isUpdate)) {
        record.value = (await getMchQrcode({ id: data.record.id })) || {}
      }
      if (!configValue?.mchPayQrcodePrefix || !configValue?.mchPayQrcodeSuffix) {
        createMessage.warning("尚未配置交易的码牌地址, 请联系管理员")
      }

      updateSchema([
        {
          field: "entryPage",
          componentProps: ({}) => {
            return {
              type: "radio",
              dictType: "scanMchQrcodeEntryPage",
              onChange: (value: any, _) => {
                console.log("-----", value)
              },
            }
          },
        },
      ])

      setFieldsValue({
        ...record.value,
        qrcodePrefix: configValue?.mchPayQrcodePrefix,
        qrcodeSuffix: configValue?.mchPayQrcodeSuffix,
      })
    } finally {
      setDrawerProps({ loading: false })
    }
  })

  const getTitle = computed(() => (!unref(isUpdate) ? "新增商户码牌" : "编辑商户码牌"))

  async function handleSubmit() {
    try {
      let values = await validate()
      delete values.qrcodePrefix
      delete values.qrcodeSuffix
      setDrawerProps({ confirmLoading: true })

      await saveOrUpdateMchQrcode({ ...values }, unref(isUpdate))
      closeDrawer()
      createMessage.success(`${getTitle.value}成功`)
      emit("success")
    } finally {
      setDrawerProps({ confirmLoading: false })
    }
  }

  const getTodayBatchNo = (model: any, field: string) => {
    model[field] = dateUtil(new Date()).format("YYYYMMDD") + "01"
  }
</script>
